package com.xiaozhu.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient 工具类，支持 GET、POST 表单和 POST JSON
 * 兼容 HttpClient 5.x
 * @author 朱慧军
 * @version 2.0
 */
@Slf4j
public class HttpClientUtils {

    /**
     * GET 请求
     */
    public static String doGet(String url, Map<String, String> params) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder uriBuilder = new URIBuilder(url);

            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                }
            }

            HttpGet httpGet = new HttpGet(uriBuilder.build());
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                if (response.getCode() == 200) {
                    return EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            }
        } catch (Exception e) {
            log.error("doGet_error:", e);
        }
        return null;
    }

    /**
     * POST 表单请求
     */
    public static String doPost(String url, Map<String, String> params) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                List<NameValuePair> nvps = new ArrayList<>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getCode() == 200) {
                    return EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            }
        } catch (Exception e) {
            log.error("doPost_error:", e);
        }
        return null;
    }

    /**
     * POST JSON 请求
     */
    public static String doPostJson(String url, Map<String, String> params) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    jsonObject.put(entry.getKey(), entry.getValue());
                }

                // HttpClient 5.x 推荐用 ContentType.APPLICATION_JSON
                StringEntity stringEntity = new StringEntity(
                        jsonObject.toString(),
                        ContentType.APPLICATION_JSON.withCharset("UTF-8")
                );
                httpPost.setEntity(stringEntity);
            }

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getCode() == 200) {
                    return EntityUtils.toString(response.getEntity(), "UTF-8");
                } else {
                    log.warn("doPostJson 请求失败，状态码：{}", response.getCode());
                }
            }
        } catch (Exception e) {
            log.error("doPostJson_error:", e);
        }
        return null;
    }
}
